<template>
  <div>
    <div>
      <el-input
        style="width: 200px; margin-right: 20px; margin-bottom: 20px"
        v-model="searchValue"
        placeholder="请输入内容"
      ></el-input>
      <el-button type="primary" @click="searchs">搜索</el-button>
    </div>
    <el-table :data="rows" border style="width: 100%">
      <el-table-column prop="_id" label="编号" width="240"> </el-table-column>
      <el-table-column prop="username" label="姓名" width="120">
      </el-table-column>
      <el-table-column label="管理员" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.role">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址" width="240">
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="120"> </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="update(scope.row)"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="curPage"
      :page-size="3"
      layout=" prev, pager, next"
      :total="total"
    >
    </el-pagination>
    <Update
      v-if="isUpdate"
      @click="click"
      @sureUpdate="sureUpdate"
      @changeValue="changeName"
      :title="title"
      :name="name"
      :address="address"
      :id="id"
      :phone="phone"
      :type="'user'"
    />
  </div>
</template>

<script>
import { createNamespacedHelpers } from "vuex";
const { mapActions, mapState, mapMutations } = createNamespacedHelpers("users");
export default {
  mounted() {
    this.get();
  },
  computed: {
    ...mapState(["rows", "total", "curPage", "eachPage", "maxPage"]),
  },
  methods: {
    ...mapActions(["get"]),
    ...mapMutations(["setCurPage", "updates", "searchUsers"]),
    update(row) {
      // console.log(row);
      this.isUpdate = true;
      this.id = row._id;
      this.name = row.username;
      this.address = row.address == undefined ? "" : row.address;
      this.phone = row.phone == undefined ? "" : row.phone;
    },
    handleCurrentChange(val) {
      this.setCurPage(val);
    },
    click() {
      this.isUpdate = false;
      this.id = "";
      this.name = "";
      this.address = "";
      this.phone = "";
    },
    async sureUpdate(data) {
      await this.updates(data);
      this.isUpdate = false;
      this.get();
    },
    changeName(name) {
      this.name = name;
    },
    async searchs() {
      const name = this.searchValue.trim();
      await this.searchUsers(name);
    },
  },

  data() {
    return {
      isUpdate: false,
      title: "编辑用户",
      name: "",
      address: "",
      id: "",
      phone: "",
      searchValue: "",
    };
  },
  watch: {
    curPage() {
      this.get();
    },
  },
};
</script>
